package org.example.what_mall.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.PostConstruct;
import org.example.what_mall.exception.GlobalCode;
import org.example.what_mall.exception.GlobalException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class JWTConfig {
    @Value("${my.secret-key}")
    public String secretKey;

    private static final Long JWT_TTL = 7 * 24 * 60 * 1000L;

    private Algorithm algorithm;

    @PostConstruct
    public void init() {
        algorithm = Algorithm.HMAC256(secretKey);
    }

    public String encode(Map<String, Object> claims) {
        return JWT.create()
                .withPayload( claims)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + JWT_TTL))
                .sign(algorithm);
    }

    public DecodedJWT decode(String token) {
        try{
            return JWT.require(algorithm).build().verify(token);
        }
        catch (SignatureVerificationException | TokenExpiredException e){
//            签名验证异常
            throw new GlobalException(GlobalCode.UNAUTHORIZED);
        }
    }

}
